<?php

namespace User\Model;

use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Adapter\Adapter;
use Library\String;

class UserModel {

    const tbl_member = 'zend_member';


    private $adapter;
    
    private $userGateway;



    public function __construct(Adapter $adapter) {
        
        $this->adapter = $adapter;
        
        $this->userGateway = new TableGateway(self::tbl_member, $this->adapter);
    }
    
    public function getAdapter() {
        return $this->adapter;
    }
    
    public function getTableMemberName() {
        return self::tbl_member;
    }
    
    public function registerUser($userData) {
        $aryUser['member_email'] = $userData['member_email'];
        $aryUser['member_password'] = String::createPassword($userData['member_password']);
        $aryUser['member_token'] = String::createToken();
        $aryResult = array();
        $aryResult['isOk'] = $this->userGateway->insert($aryUser);
        $aryResult['user_data'] = $aryUser;
        return $aryResult;
    }
    
    public function checkUserByToken($token) {
        $select = $this->userGateway->getSql()->select()
                    ->columns(array('member_id'));
        $select->where(array('member_del_flag = ?' => 0))
               ->where(array('member_active = ?' => 0))
               ->where(array('member_confirm = ?' => 0))
               ->where(array('member_token = ?' => $token));
        
        $result = $this->userGateway->selectWith($select);
        
        $data = $result->toArray();
        
        if(isset($data[0]['member_id'])){
            return true;
        }
        return false;
    }
    
    public function activeUser($token) {
        
        $aryUser = array();
        $aryUser['member_active'] = 1;
        $aryUser['member_confirm'] = 1;
        $result = $this->userGateway->update($aryUser, array('member_token = ? ' => $token));
        return $result;
    }
    
}
